package pl.umk.mat.fred.unicore.urc.storagemanagement.actions;

import java.net.MalformedURLException;
import java.net.URL;

import org.eclipse.jface.action.Action;
import org.eclipse.jface.resource.ImageDescriptor;

import pl.umk.mat.fred.unicore.urc.storagemanagement.StorageManagementActivator;
import pl.umk.mat.fred.unicore.urc.storagemanagement.views.TimeMeterView;

public class RunTimeMeterThreadAction extends Action {

	private String ENABLED_RUN_ICON = "enabledRunIcon";
	private String DISABLED_RUN_ICON = "disabledRunIcon";
	
	private TimeMeterView view = null;
	
	public RunTimeMeterThreadAction(TimeMeterView view) {
		this.view = view;
		this.setText("Run Time Meter");
		this.setToolTipText("Run Time Meter");
		this.setImageDescriptor(getImage());
		this.checkEnabled();
	}
	
	@Override
	public void run() {
		StorageManagementActivator.getDefault().getTimeMeter().setWorking(true);
		Thread timeMeterThread = StorageManagementActivator.getDefault().getTimeMeterThread();
		if (timeMeterThread.isAlive()) {
			timeMeterThread.interrupt();
		} else {
			timeMeterThread.start();
		}
		getImage();
		checkEnabled();
		view.getStopTimeMeterThreadAction().refreshState();
	}
	
	private void checkEnabled() {
		if (StorageManagementActivator.getDefault().isTimeMeterWorking()) {
			setEnabled(false);
		} else {
			setEnabled(true);
		}
	}
	
	private ImageDescriptor getImage() {
		if (StorageManagementActivator.getDefault().isTimeMeterWorking()) {
			ImageDescriptor image = (ImageDescriptor)StorageManagementActivator.getDefault().getObjectFromCache(DISABLED_RUN_ICON);
			if (image == null) {
			  image = ImageDescriptor.createFromURL(StorageManagementActivator.getDefault().getBundle().getEntry("/icons/runIconDisabled.png"));
			  StorageManagementActivator.getDefault().setObjectToCache(DISABLED_RUN_ICON, image);
			}
			return image;
		} else {
			ImageDescriptor image = (ImageDescriptor)StorageManagementActivator.getDefault().getObjectFromCache(ENABLED_RUN_ICON);
			if (image == null) {
			  image = ImageDescriptor.createFromURL(StorageManagementActivator.getDefault().getBundle().getEntry("/icons/runIcon.png"));
			  StorageManagementActivator.getDefault().setObjectToCache(ENABLED_RUN_ICON, image);
			}
			return image;
		}
	}
	
	public void refreshState() {
		setImageDescriptor(getImage());
		checkEnabled();
	}
}
